/**
 * Project Name:demo
 * File Name:SpringThreadPool.java
 * Package Name:com.cloud.demo.thread
 * Date:2016年3月9日下午1:54:39
 * Copyright (c) 2016, LiHao All Rights Reserved.
 *
*/

package com.cloud.demo.thread;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.task.TaskExecutor;

/**
 * ClassName:SpringThreadPool <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2016年3月9日 下午1:54:39 <br/>
 * @author   LiHao
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
public class SpringThreadPool {
	private static Logger logger = LoggerFactory.getLogger(SpringThreadPool.class);
	private TaskExecutor taskExecutor;
	public void setTaskExecutor(TaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	} 
	// 每秒并发访问控制数量  
    final static int MAX_QPS1 = 50;  
    // 并发控制信号量  
    final static Semaphore semaphore1 = new Semaphore(MAX_QPS1);  
    // 监控每秒并发访问次数（理论上accessCount.get() <= MAX_QPS）  
    final static AtomicInteger accessCount1 = new AtomicInteger(0);
    final static int MAX_QPS2 = 10;  
    final static Semaphore semaphore2 = new Semaphore(MAX_QPS2);  
    // 监控每秒并发访问次数（理论上accessCount.get() <= MAX_QPS）  
    final static AtomicInteger accessCount2 = new AtomicInteger(0);
 
    final static int MAX_QPS3 = 20;
    final static Semaphore semaphore3 = new Semaphore(MAX_QPS3);  
    // 监控每秒并发访问次数（理论上accessCount.get() <= MAX_QPS）  
    final static AtomicInteger accessCount3 = new AtomicInteger(0); 
    public SpringThreadPool(){
    	logger.info("初始化");
    }
    // 模拟远程访问  
    private static void remoteCall(int i, int j,String flag) {  
//        System.out.println(String.format("%s - %s: %d %d", new Date(), Thread.currentThread(), i, j));  
    	logger.info(flag+"s_"+String.format("%s - %s: %d %d", new Date(), Thread.currentThread(), i, j));
    	try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
    	logger.info(flag+"e_"+String.format("%s - %s: %d %d", new Date(), Thread.currentThread(), i, j));
    }  
    public static void releaseWork() { // 每秒release一次  
        // release semaphore thread  
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {  
            @Override  
            public void run() {  
            	
                int count1=accessCount1.get();
            	logger.debug("【releaseWork1】>>"+count1);
            	accessCount1.set(0);  
                semaphore1.release(count1); //信号量加上用了多少
//                int count2=accessCount2.get();
//            	logger.debug("【releaseWork2】>>"+count2);
//            	accessCount2.set(0);  
//                semaphore2.release(count2); //信号量加上用了多少
//                int count3=accessCount3.get();
//            	logger.debug("【releaseWork3】>>"+count3);
//            	accessCount3.set(0);  
//                semaphore3.release(count3); //信号量加上用了多少
            }  
        }, 0, 1000, TimeUnit.MILLISECONDS);  
    }  
  
	/**
	 * 异步发送
	 */
	public void postDataByAsynMode(final int i,final int j){
//		logger.debug("【异步发送】");
		taskExecutor.execute(new Runnable(){
			public void run(){
				remoteCall(i,j,"postDataByAsynMode");
			}
		});
	}
	public void postDataByAsynMode1(final int i,final int j){
		logger.debug("【异步发送1】");
		taskExecutor.execute(new Runnable(){
			public void run(){
				semaphore1.acquireUninterruptibly(1);  //获取许可 许可减1
                accessCount1.incrementAndGet();  //加1
				remoteCall(i,j,"postDataByAsynMode1");
			}
		});
	}
	public void postDataByAsynMode2(final int i,final int j){
//		logger.debug("【异步发送2】");
		taskExecutor.execute(new Runnable(){
			public void run(){
				semaphore2.acquireUninterruptibly(1);  //获取许可 许可减1
                accessCount2.incrementAndGet();  //加1
				remoteCall(i,j,"postDataByAsynMode2");
			}
		});
	}
	public void postDataByAsynMode3(final int i,final int j){
//		logger.debug("【异步发送】");
		taskExecutor.execute(new Runnable(){
			public void run(){
				semaphore3.acquireUninterruptibly(1);  //获取许可 许可减1
                accessCount3.incrementAndGet();  //加1
				remoteCall(i,j,"postDataByAsynMode3");
			}
		});
	}
	public static void main(String[] args) throws Exception{
		
	}

}

